package spring;

import spring.annotation.Autowired;
import spring.annotation.Value;
import spring.utils.ClassUtil;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Properties;

/**
 * @ProjectName: Spring
 * @Package: spring
 * @ClassName: AutowiredAnnotationBeanPostProcessor
 * @Author: zxh
 * @Description:
 * @Date: 2022/3/11 17:21
 * @Version: 1.0
 */
public class AutowiredAnnotationBeanPostProcessor implements BeanPostProcessor, PriorityOrdered {

    private final static Properties env = new Properties();

    static {
        InputStream resourceAsStream = ApplicationContext.class.getResourceAsStream("/applicationContext.properties");
        try {
            env.load(resourceAsStream);
            resourceAsStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void postProcessProperties(Object instance, Class clazz, DefaultListableBeanFactory beanFactory) {
        for (Field declaredField : clazz.getDeclaredFields()) {
            if (declaredField.isAnnotationPresent(Autowired.class)) {
                /*此处简单的根据名字进行依赖注入*/
                Object bean = beanFactory.getBean(declaredField.getName());
                ClassUtil.setField(declaredField, instance, bean);
            }
            if (declaredField.isAnnotationPresent(Value.class)) {
                /*未实现类型转换器，仅能注入String类型*/
                Value annotation = declaredField.getAnnotation(Value.class);
                String value = annotation.value();
                String substring = value.substring(2, value.indexOf("}"));
                String property = env.getProperty(substring);
                ClassUtil.setField(declaredField, instance, property);
            }
        }
    }
}
